package qj.tool.console;

import qj.tool.console.exception.InvalidCommandFormatException;

import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Created by QuanLA
 * Date: Feb 28, 2006
 * Time: 5:24:01 PM
 */
public class ConsoleUtil {
    private static final Pattern ptnKey = Pattern.compile("\\w+");
    /**
     *
     * @param command
     * @return command key of a given command
     */
    public static String getCommandKey(String command) throws InvalidCommandFormatException {
        Matcher matcher = ptnKey.matcher(command);
        if (matcher.find())
            return matcher.group();
        else
            throw new InvalidCommandFormatException();
    }
    
    public static HashMap getNamedArguments(String[] args) {
		HashMap map = new HashMap();
    	for (int i = 0; i < args.length - 1; i++) {
			if (args[i].startsWith("-")) {
				map.put(args[i].substring(1), args[i + 1]);
				i++;
			}
		}
    	return map;
    }

    /**
     * Sort the command by their type and name
     * @param commands
     */
    static void sortCommands(IConsoleCommand[] commands) {
        IConsoleCommand commandTemp;
        for (int i = 0; i < commands.length; i++) {
            for (int j = i; j < commands.length; j++) {

                if ((commands[i] instanceof IConsoleCommandExit && !(commands[j] instanceof IConsoleCommandExit))
                        || commands[i].commandKey().compareTo(commands[j].commandKey()) > 0) {

                    commandTemp   = commands[i];
                    commands[i] = commands[j];
                    commands[j]  = commandTemp;
                }
            }

        }
    }
}
